<template>
  <div class="dynamic-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 动态生成的字段 -->
      <template v-for="field in fields" :key="field.name">
        <!-- 文本输入框 -->
        <el-form-item
          v-if="field.type === 'text' || field.type === 'email' || field.type === 'url'"
          :label="field.label"
          :prop="field.name"
        >
          <el-input
            v-model="formData[field.name]"
            :type="field.type"
            :placeholder="field.placeholder || `请输入${field.label}`"
            clearable
          />
        </el-form-item>

        <!-- 数字输入框 -->
        <el-form-item
          v-else-if="field.type === 'number'"
          :label="field.label"
          :prop="field.name"
        >
          <el-input-number
            v-model="formData[field.name]"
            :placeholder="field.placeholder || `请输入${field.label}`"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 多行文本 -->
        <el-form-item
          v-else-if="field.type === 'textarea'"
          :label="field.label"
          :prop="field.name"
        >
          <el-input
            v-model="formData[field.name]"
            type="textarea"
            :rows="field.settings?.rows || 4"
            :placeholder="field.placeholder || `请输入${field.label}`"
          />
        </el-form-item>

        <!-- 下拉选择 -->
        <el-form-item
          v-else-if="field.type === 'select'"
          :label="field.label"
          :prop="field.name"
        >
          <el-select
            v-model="formData[field.name]"
            :placeholder="field.placeholder || `请选择${field.label}`"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="option in field.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="option.disabled"
            />
          </el-select>
        </el-form-item>

        <!-- 单选按钮 -->
        <el-form-item
          v-else-if="field.type === 'radio'"
          :label="field.label"
          :prop="field.name"
        >
          <el-radio-group v-model="formData[field.name]">
            <el-radio
              v-for="option in field.options"
              :key="option.value"
              :label="option.value"
              :disabled="option.disabled"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 复选框 -->
        <el-form-item
          v-else-if="field.type === 'checkbox'"
          :label="field.label"
          :prop="field.name"
        >
          <el-checkbox-group v-model="formData[field.name]">
            <el-checkbox
              v-for="option in field.options"
              :key="option.value"
              :label="option.value"
              :disabled="option.disabled"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 日期选择 -->
        <el-form-item
          v-else-if="field.type === 'date'"
          :label="field.label"
          :prop="field.name"
        >
          <el-date-picker
            v-model="formData[field.name]"
            type="date"
            :placeholder="field.placeholder || `请选择${field.label}`"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 日期时间选择 -->
        <el-form-item
          v-else-if="field.type === 'datetime'"
          :label="field.label"
          :prop="field.name"
        >
          <el-date-picker
            v-model="formData[field.name]"
            type="datetime"
            :placeholder="field.placeholder || `请选择${field.label}`"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item
          v-else-if="field.type === 'image'"
          :label="field.label"
          :prop="field.name"
        >
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :show-file-list="false"
            :on-success="(response) => handleImageSuccess(response, field.name)"
            :on-error="(error) => handleUploadError(error, field.name)"
            :before-upload="beforeImageUpload"
          >
            <img v-if="formData[field.name]" :src="formData[field.name]" class="image-preview" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 文件上传 -->
        <el-form-item
          v-else-if="field.type === 'file'"
          :label="field.label"
          :prop="field.name"
        >
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :on-success="(response) => handleFileSuccess(response, field.name)"
            :on-error="(error) => handleUploadError(error, field.name)"
            :before-upload="beforeFileUpload"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">{{ field.description || '请选择要上传的文件' }}</div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 富文本编辑器 -->
        <el-form-item
          v-else-if="field.type === 'editor'"
          :label="field.label"
          :prop="field.name"
        >
          <div class="editor-container">
            <el-input
              v-model="formData[field.name]"
              type="textarea"
              :rows="8"
              :placeholder="field.placeholder || `请输入${field.label}`"
            />
            <div class="editor-tip">富文本编辑器功能开发中，暂时使用文本域</div>
          </div>
        </el-form-item>

        <!-- 默认文本输入 -->
        <el-form-item
          v-else
          :label="field.label"
          :prop="field.name"
        >
          <el-input
            v-model="formData[field.name]"
            :placeholder="field.placeholder || `请输入${field.label}`"
            clearable
          />
        </el-form-item>
      </template>

      <!-- 如果没有字段配置，显示提示 -->
      <div v-if="!loading && fields.length === 0" class="no-fields">
        <el-empty description="该区块暂无字段配置">
          <el-button type="primary" @click="$emit('configure-fields')">
            配置字段
          </el-button>
        </el-empty>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { validateImageFile, validateGeneralFile } from '@/config/upload'
import { blockApi } from '@/api/block'
import { getToken } from '@/utils/auth'

// Props
interface Props {
  blockId: number
  modelValue?: Record<string, any>
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({})
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: Record<string, any>]
  'configure-fields': []
}>()

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()
const fields = ref<any[]>([])
const formData = ref<Record<string, any>>({})
const uploadUrl = ref('/cms/admin/attachment/upload') // 使用正确的上传接口

// 上传请求头
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${getToken()}`
}))

// 上传数据
const uploadData = computed(() => ({
  siteId: 1, // 默认站点ID，后续可以从props或context获取
  userId: 1  // 默认用户ID，后续可以从用户store获取
}))

// 计算属性
const formRules = computed<FormRules>(() => {
  const rules: FormRules = {}
  
  fields.value.forEach(field => {
    const fieldRules: any[] = []
    
    // 必填验证
    if (field.required) {
      fieldRules.push({
        required: true,
        message: `${field.label}不能为空`,
        trigger: field.type === 'select' ? 'change' : 'blur'
      })
    }
    
    // 类型验证
    if (field.type === 'email') {
      fieldRules.push({
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: 'blur'
      })
    }
    
    // 自定义验证规则
    if (field.validation) {
      if (field.validation.minLength) {
        fieldRules.push({
          min: field.validation.minLength,
          message: `${field.label}长度不能少于${field.validation.minLength}个字符`,
          trigger: 'blur'
        })
      }
      if (field.validation.maxLength) {
        fieldRules.push({
          max: field.validation.maxLength,
          message: `${field.label}长度不能超过${field.validation.maxLength}个字符`,
          trigger: 'blur'
        })
      }
      if (field.validation.pattern) {
        fieldRules.push({
          pattern: new RegExp(field.validation.pattern),
          message: field.validation.message || `${field.label}格式不正确`,
          trigger: 'blur'
        })
      }
    }
    
    if (fieldRules.length > 0) {
      rules[field.name] = fieldRules
    }
  })
  
  return rules
})

// 监听表单数据变化
watch(formData, (newValue) => {
  emit('update:modelValue', newValue)
}, { deep: true })

// 监听外部数据变化
watch(() => props.modelValue, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    formData.value = { ...newValue }
  }
}, { immediate: true, deep: true })

// 字段值处理方法
const fixedFields = ['title', 'subtitle', 'content', 'image', 'link', 'target']

// 创建一个计算属性来处理字段值的映射
const fieldValues = computed(() => {
  const values: Record<string, any> = {}

  fields.value.forEach(field => {
    if (fixedFields.includes(field.name)) {
      values[field.name] = formData.value[field.name] || ''
    } else {
      values[field.name] = formData.value.attributes?.[field.name] || ''
    }
  })

  return values
})

const getFieldValue = (fieldName: string) => {
  if (fixedFields.includes(fieldName)) {
    return formData.value[fieldName] || ''
  } else {
    return formData.value.attributes?.[fieldName] || ''
  }
}

const setFieldValue = (fieldName: string, value: any) => {
  if (fixedFields.includes(fieldName)) {
    formData.value[fieldName] = value
  } else {
    if (!formData.value.attributes) {
      formData.value.attributes = {}
    }
    formData.value.attributes[fieldName] = value
  }
}

// 方法
const loadFields = async () => {
  loading.value = true
  try {
    console.log('正在加载区块字段配置，blockId:', props.blockId)
    const response = await blockApi.getFormSchema(props.blockId)
    console.log('获取字段配置响应:', response)

    if (response && response.code === 0) {
      fields.value = response.data?.fields || []
      console.log('解析到的字段:', fields.value)
      initFormData()
    } else {
      console.error('获取字段配置失败，响应:', response)
      ElMessage.error(response?.msg || '获取字段配置失败')
    }
  } catch (error) {
    console.error('加载字段配置失败:', error)
    ElMessage.error('加载字段配置失败: ' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    loading.value = false
  }
}

const initFormData = () => {
  const data: Record<string, any> = {}

  // 为所有字段设置默认值（扁平结构）
  fields.value.forEach(field => {
    if (field.defaultValue !== undefined && field.defaultValue !== null) {
      data[field.name] = field.defaultValue
    } else if (field.type === 'checkbox') {
      data[field.name] = []
    } else {
      data[field.name] = ''
    }
  })

  // 合并外部传入的数据
  const externalData = { ...props.modelValue }

  // 处理字段名映射：后端字段名 -> 前端字段名
  if (externalData.imageUrl) {
    externalData.image = externalData.imageUrl
    delete externalData.imageUrl
  }
  if (externalData.linkUrl) {
    externalData.link = externalData.linkUrl
    delete externalData.linkUrl
  }
  if (externalData.summary && !externalData.subtitle) {
    externalData.subtitle = externalData.summary
  }

  // 处理外部数据中的attributes，将其展开到扁平结构
  if (externalData.attributes) {
    let attributesData = {}
    if (typeof externalData.attributes === 'string') {
      try {
        attributesData = JSON.parse(externalData.attributes)
      } catch (e) {
        console.warn('解析attributes失败:', e)
        attributesData = {}
      }
    } else {
      attributesData = externalData.attributes
    }

    // 将attributes中的数据展开到根级别
    Object.assign(externalData, attributesData)
    delete externalData.attributes
  }

  formData.value = { ...data, ...externalData }
}

const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

const resetFields = () => {
  formRef.value?.resetFields()
  initFormData()
}

// 获取格式化的表单数据（转换为BlockItem格式）
const getFormattedData = () => {
  const result: Record<string, any> = {}
  const attributes: Record<string, any> = {}

  // 分离固定字段和动态字段
  Object.keys(formData.value).forEach(key => {
    if (fixedFields.includes(key)) {
      // 直接使用原始字段名，不进行映射
      result[key] = formData.value[key]
    } else {
      attributes[key] = formData.value[key]
    }
  })

  // 如果有动态字段，将其序列化为JSON字符串
  if (Object.keys(attributes).length > 0) {
    result.attributes = JSON.stringify(attributes)
  }

  return result
}

// 文件上传处理
const handleImageSuccess = (response: any, fieldName: string) => {
  if (response.code === 0) {
    formData.value[fieldName] = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

const handleFileSuccess = (response: any, fieldName: string) => {
  if (response.code === 0) {
    formData.value[fieldName] = response.data.url
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.msg || '文件上传失败')
  }
}

// 上传错误处理
const handleUploadError = (error: any, fieldName: string) => {
  console.error('上传失败:', error)
  ElMessage.error(`${fieldName}上传失败: ${error.message || '网络错误'}`)
}

const beforeImageUpload = (file: File) => {
  // 使用统一的图片验证
  const validation = validateImageFile(file)
  if (!validation.valid) {
    ElMessage.error(validation.error!)
    return false
  }
  return true
}

const beforeFileUpload = (file: File) => {
  // 使用统一的文件验证
  const validation = validateGeneralFile(file)
  if (!validation.valid) {
    ElMessage.error(validation.error!)
    return false
  }
  return true
}

// 暴露方法给父组件
defineExpose({
  validate,
  resetFields,
  formData,
  getFormattedData
})

// 生命周期
onMounted(() => {
  loadFields()
})
</script>

<style scoped>
.dynamic-form {
  padding: 20px;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.image-preview {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.editor-container {
  position: relative;
}

.editor-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.no-fields {
  text-align: center;
  padding: 40px 0;
}
</style>
